package com.commons.dbutils.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;

/**
 * 通过AES算法对文本进行加密解密
 */
public class AESUtil {

	private String iv = "01M2w3q4b5c6t7k8";
	// 算法参数 : //使用CBC模式，需要一个向量iv，可增加加密算法的强度

	private SecretKey key; // 加密密钥
	private AlgorithmParameterSpec paramSpec; // 算法参数
	private Cipher ecipher; // 加密算法
	private byte[] keyBytes = null;
	private SecureRandomEnum secureRandomEnum = SecureRandomEnum.DEFAULT;

	public AESUtil(byte[] ukey) {
		if (ukey == null) {
			throw new IllegalArgumentException("keyByte cannot be null");
		}
		this.keyBytes = ukey;
	}

	public AESUtil(String ukey) {
		if (ukey == null) {
			throw new IllegalArgumentException("keyByte cannot be null");
		}
		this.keyBytes = ukey.getBytes();
	}

	public AESUtil(String ukey, boolean autoInit)
			throws NoSuchAlgorithmException, NoSuchPaddingException {
		if (ukey == null) {
			throw new IllegalArgumentException("keyByte cannot be null");
		}
		this.keyBytes = ukey.getBytes();
		if (autoInit) {
			this.init(null, iv, true, secureRandomEnum);
		}
	}

	public void init(AESEnum aesEnum, String newIv, boolean openIv,
			SecureRandomEnum secureRandomEnum) throws NoSuchAlgorithmException,
			NoSuchPaddingException {
		if (keyBytes == null) {
			throw new IllegalArgumentException("keyByte cannot be null");
		}
		KeyGenerator kgen = null;
		// 为指定算法生成一个密钥生成器对象。
		kgen = KeyGenerator.getInstance("AES");
		if (SecureRandomEnum.DEFAULT.equals(secureRandomEnum)) {
			kgen.init(128, new SecureRandom(keyBytes));
		} else {
			SecureRandom secureRandom = SecureRandom
					.getInstance(secureRandomEnum.getName());
			secureRandom.setSeed(keyBytes);
			kgen.init(128, secureRandom);
		}

		// 使用KeyGenerator生成（对称）密钥。
		key = kgen.generateKey();
		// 使用iv中的字节作为IV来构造一个 算法参数。

		if (openIv) {
			this.iv = newIv != null ? newIv : iv;
			paramSpec = new IvParameterSpec(this.iv.getBytes());
		}

		// 生成一个实现指定转换的 Cipher 对象
		if (aesEnum == null || AESEnum.ECB.equals(aesEnum)) {
			ecipher = Cipher.getInstance("AES"); // "算法/模式/补码方式"
		} else {
			ecipher = Cipher.getInstance(new StringBuffer("AES/")
					.append(aesEnum.getName()).append("/PKCS5Padding")
					.toString()); // "算法/模式/补码方式"
		}
	}

	/**
	 * 加密，使用指定数据源生成密钥，使用用户数据作为算法参数进行AES加密
	 * 
	 * @param msg
	 *            加密的数据
	 * @return
	 * @throws InvalidAlgorithmParameterException
	 * @throws InvalidKeyException
	 * @throws BadPaddingException
	 * @throws IllegalBlockSizeException
	 */
	public byte[] encrypt(String msg) throws InvalidKeyException,
			InvalidAlgorithmParameterException, IllegalBlockSizeException,
			BadPaddingException {
		return this.encrypt(msg.getBytes());
	}
	
	public byte[] encrypt(byte[] msg) throws InvalidKeyException,
			InvalidAlgorithmParameterException, IllegalBlockSizeException,
			BadPaddingException {
		// 用密钥和一组算法参数初始化此 cipher
		ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
		// 加密并转换成16进制字符串
		return ecipher.doFinal(msg);
	}
	
	
	
	
	/**
	 * 解密，对生成的16进制的字符串进行解密
	 * 
	 * @param value
	 *            解密的数据
	 * @return
	 */
	public String decryptFromHex(String value) {

		return this.decrypt(value);

	}
	/**
	 * 解密，对生成的16进制的字符串进行解密
	 * 
	 * @param value
	 *            解密的数据
	 * @return
	 */
	public String decryptFromBase64(String value) {
		return this.decrypt(value);
	}
	/**
	 * 解密
	 * 
	 * @param value
	 *            解密的数据
	 * @return
	 */
	public String decrypt(byte[] value) throws InvalidKeyException,
			InvalidAlgorithmParameterException, IllegalBlockSizeException,
			BadPaddingException {

		ecipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
		return new String(ecipher.doFinal(value));

	}

	

	public static void main(String[] args) throws NoSuchAlgorithmException,
			NoSuchPaddingException, InvalidKeyException,
			IllegalBlockSizeException, BadPaddingException,
			UnsupportedEncodingException {
		AESUtil a = new AESUtil("kskskskssk", AESEnum.ECB);
		a.openIv("01M2w3q4b5c6t7k8", false);
		System.out.println(Hex.encodeHexString(a.encrypt("测试")));
		// System.out.println(AESEnum.ECB.equals(AESEnum.CBC));
		// System.out.println(Hex.encodeHexString(AESUtil.encrypt("测试",
		// "kskskskssk")));

	}
}
